%%% @doc
%%% 自动下载deps到checkouts目录
%%%
%%% ```
%%% 代码参考 rebar_prv_install_deps.erl 文件来修改实现
%%% '''
%%% @end
-module(rebar3_deps_prv_save).

-export([init/1,
    do/1,
    format_error/1]).

-define(PROVIDER, 'save-deps').
-define(DEPS, [{default, app_discovery}]).
%%-define(DEPS, [app_discovery]).
-define(SHORT_DESC, "SHORT_DESC").
-define(DESC, "long desc\n"
"  {gpb_opts,["
"    {i, \"path/to/proto_dir\"},"
"    {f, \[list of wanted protobuf files\]},"
"    {module_name_suffix, \"_pb\"},"
"    {o_erl, \"path/to/out_src\"},"
"    {o_hrl, \"path/to/out_include\"},"
"    {strings_as_binaries, true},"
"    type_specs]}).").

%% ===================================================================
%% Public API
%% ===================================================================
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    Provider = providers:create([
        {name, ?PROVIDER},            % The 'user friendly' name of the task
        {module, ?MODULE},            % The module implementation of the task
        {bare, true},                 % The task can be run by the user, always true
        {deps, ?DEPS},                % The list of dependencies
        {opts, []},                   % list of options understood by the plugin
        {example, "rebar3 save-deps"},
        {short_desc, ?SHORT_DESC},
        {desc, ?DESC}
    ]),
    {ok, rebar_state:add_provider(State, Provider)}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()}.
do(State) ->
    try
        State1 = project_plugins_install(State),
        State2 = top_level_install(State1),

        Profiles = rebar_state:current_profiles(State2),
        {_Apps, _State3} = deps_per_profile(Profiles, false, State2),
        %% 这里返回 State 避免影响后面的处理
        {ok, State}
    catch
        %% maybe_fetch will maybe_throw an exception to break out of some loops
        _:{error, Reason} ->
            {error, Reason}
    end.

%% @doc convert a given exception's payload into an io description.
-spec format_error(any()) -> iolist().
format_error({dep_app_not_found, AppDir, AppName}) ->
    io_lib:format("Dependency failure: Application ~ts not found at the top level of directory ~ts", [AppName, AppDir]);
format_error({load_registry_fail, Dep}) ->
    io_lib:format("Error loading registry to resolve version of ~ts. Try fixing by running 'rebar3 update'", [Dep]);
format_error({bad_constraint, Name, Constraint}) ->
    io_lib:format("Unable to parse version for package ~ts: ~ts", [Name, Constraint]);
format_error({parse_dep, Dep}) ->
    io_lib:format("Failed parsing dep ~p", [Dep]);
format_error({not_rebar_package, Package, Version}) ->
    io_lib:format("Package not buildable with rebar3: ~ts-~ts", [Package, Version]);
format_error({missing_package, Package, Version}) ->
    io_lib:format("Package not found in registry: ~ts-~ts", [Package, Version]);
format_error({missing_package, Package}) ->
    io_lib:format("Package not found in registry: ~ts", [Package]);
format_error({cycles, Cycles}) ->
    Prints = [["applications: ",
        [io_lib:format("~ts ", [Dep]) || Dep <- Cycle],
        "depend on each other\n"]
        || Cycle <- Cycles],
    ["Dependency cycle(s) detected:\n", Prints];
format_error(Reason) ->
    io_lib:format("~p", [Reason]).


%% ===================================================================
%% Internal functions
%% ===================================================================

%% @doc Allows other providers to install deps in a given profile
%% manually, outside of what is provided by rebar3's deps tuple.
-spec handle_deps_as_profile(Profile, State, Deps, Upgrade) -> {Apps, State} when
    Profile :: atom(),
    State :: rebar_state:t(),
    Deps :: [tuple() | atom() | binary()], % TODO: meta to source() | lock()
    Upgrade :: boolean(),
    Apps :: [rebar_app_info:t()].
handle_deps_as_profile(Profile, State, Deps, Upgrade) ->
    Locks = [],
    Level = 0,
    DepsDir = profile_dep_dir(State, Profile),
    Deps1 = rebar_app_utils:parse_deps(DepsDir, Deps, State, Locks, Level),
    ProfileLevelDeps = [{Profile, Deps1, Level}],
    RootSeen = sets:from_list([rebar_app_info:name(AppInfo)
        || AppInfo <- rebar_state:project_apps(State)]),
    handle_profile_level(ProfileLevelDeps, [], RootSeen, RootSeen, Upgrade, Locks, State).

%% finds all the deps in `{deps, ...}` for each profile provided.
deps_per_profile(Profiles, Upgrade, State) ->
    Level = 0,
    Locks = rebar_state:get(State, {locks, default}, []),
    Deps = lists:foldl(fun(Profile, DepAcc) ->
        [parsed_profile_deps(State, Profile, Level) | DepAcc]
                       end, [], Profiles),
    RootSeen = sets:from_list([rebar_app_info:name(AppInfo)
        || AppInfo <- rebar_state:project_apps(State)]),
    handle_profile_level(Deps, [], RootSeen, RootSeen, Upgrade, Locks, State).

parsed_profile_deps(State, Profile, Level) ->
    ParsedDeps1 = rebar_state:get(State, {parsed_deps, Profile}, []),
    %% 把root层的deps修改为 _checkouts 目录
    CheckoutDir = rebar_dir:checkouts_dir(State),
    ParsedDeps2 =
        lists:foldl(
            fun(App, Acc) ->
                Dir = rebar_utils:to_list(filename:join(CheckoutDir, rebar_app_info:name(App))),
                App1 = rebar_app_info:dir(App, Dir),
                App2 = rebar_app_info:fetch_dir(App1, Dir),
                App3 = rebar_app_info:out_dir(App2, Dir),
                [App3 | Acc]
            end, [], ParsedDeps1),
    {Profile, ParsedDeps2, Level}.

%% Level-order traversal of all dependencies, across profiles.
%% If profiles x,y,z are present, then the traversal will go:
%% x0, y0, z0, x1, y1, z1, ..., xN, yN, zN.
%%
%% There are two 'seen' sets: one for the top-level apps (`RootSeen') and
%% one for all dependencies (`Seen'). The former is used to know when
%% to skip the resolving of dependencies altogether (since they're already
%% top-level apps), while the latter is used to prevent reprocessing
%% deps more than one.
handle_profile_level([], Apps, _RootSeen, _Seen, _Upgrade, _Locks, State) ->
    {Apps, State};
handle_profile_level([{Profile, Deps, Level} | Rest], Apps, RootSeen, Seen, Upgrade, Locks, State) ->
    Deps0 = [rebar_app_utils:expand_deps_sources(Dep, State)
        || Dep <- Deps,
        %% skip top-level apps being double-declared
        not sets:is_element(rebar_app_info:name(Dep), RootSeen)],
    {Deps1, Apps1, State1, Seen1} =
        update_deps(Profile, Level, Deps0, Apps
            , State, Upgrade, Seen, Locks),
    Deps2 = case Deps1 of
                [] -> Rest;
                _ -> Rest ++ [{Profile, Deps1, Level + 1}]
            end,
    handle_profile_level(Deps2, Apps1, RootSeen, sets:union(Seen, Seen1), Upgrade, Locks, State1).


maybe_lock(Profile, AppInfo, Seen, State, Level) ->
    Name = rebar_app_info:name(AppInfo),
    case rebar_app_info:is_checkout(AppInfo) of
        false ->
            case Profile of
                default ->
                    case sets:is_element(Name, Seen) of
                        false ->
                            %% Check whether the currently existing lock is
                            %% deeper than the current one (which can happen
                            %% during an upgrade). If the current app is
                            %% shallower than the existing lock, replace the
                            %% existing lock. This prevents weird transient
                            %% lock-tree states (which would self-heal on a
                            %% later run) after a `rebar3 upgrade <app>'
                            %% command when a deep dep switches lineages for
                            %% another newer parent.
                            Locks = rebar_state:lock(State),
                            case find_app_and_level_by_name(Locks, Name) of
                                {ok, _App, LockLvl} when LockLvl =< Level ->
                                    {sets:add_element(Name, Seen), State};
                                {ok, App, _LockLvl} ->
                                    LockedApp = rebar_app_info:dep_level(AppInfo, Level),
                                    {sets:add_element(Name, Seen),
                                        rebar_state:lock(State, [LockedApp | Locks -- [App]])};
                                false ->
                                    {sets:add_element(Name, Seen),
                                        rebar_state:lock(State, rebar_app_info:dep_level(AppInfo, Level))}
                            end;
                        true ->
                            {Seen, State}
                    end;
                _ ->
                    {sets:add_element(Name, Seen), State}
            end;
        true ->
            {sets:add_element(Name, Seen), State}
    end.

update_deps(Profile, Level, Deps, Apps, State, Upgrade, Seen, Locks) ->
    lists:foldl(
        fun(AppInfo, {DepsAcc, AppsAcc, StateAcc, SeenAcc}) ->
            update_dep(AppInfo, Profile, Level,
                DepsAcc, AppsAcc, StateAcc,
                Upgrade, SeenAcc, Locks)
        end,
        {[], Apps, State, Seen},
        rebar_utils:sort_deps(Deps)).

update_dep(AppInfo, Profile, Level, Deps, Apps, State, Upgrade, Seen, Locks) ->
    %% If not seen, add to list of locks to write out
    Name = rebar_app_info:name(AppInfo),
    case sets:is_element(Name, Seen) of
        true ->
            update_seen_dep(AppInfo, Profile, Level,
                Deps, Apps,
                State, Upgrade, Seen, Locks);
        false ->
            update_unseen_dep(AppInfo, Profile, Level,
                Deps, Apps,
                State, Upgrade, Seen, Locks)
    end.

%% 修改 deps 目录为 _checkouts 目录
profile_dep_dir(State, _Profile) -> rebar_dir:checkouts_dir(State).
%%profile_dep_dir(State, _Profile)
%%    case Profile of
%%        default ->
%%            filename:join([rebar_dir:profile_dir(rebar_state:opts(State), [default]), rebar_state:get(State, deps_dir, "lib")]);
%%        _ -> rebar_dir:deps_dir(State)
%%    end.

update_seen_dep(AppInfo, _Profile, _Level, Deps, Apps, State, Upgrade, Seen, Locks) ->
    Name = rebar_app_info:name(AppInfo),
    %% If seen from lock file or user requested an upgrade
    %% don't print warning about skipping
    case lists:keymember(Name, 1, Locks) of
        false when Upgrade ->
            ok;
        false when not Upgrade ->
            {ok, SeenApp} = rebar_app_utils:find(Name, Apps),
            Source = rebar_app_info:source(AppInfo),
            case rebar_app_info:source(SeenApp) of
                Source ->
                    %% dep is the same version and checksum as the one we already saw.
                    %% meaning there is no conflict, so don't warn about it.
                    skip;
                _ ->
                    warn_skip_deps(AppInfo, State)
            end;
        true ->
            ok
    end,
    {Deps, Apps, State, Seen}.

update_unseen_dep(AppInfo, Profile, Level, Deps, Apps, State, Upgrade, Seen, Locks) ->
    {NewSeen, State1} = maybe_lock(Profile, AppInfo, Seen, State, Level),
    {_, AppInfo1} = maybe_fetch(AppInfo, Profile, Upgrade, Seen, State1),
    DepsDir = profile_dep_dir(State, Profile),
    %% 递归处理新依赖
    {AppInfo2, NewDeps, State2} =
        handle_dep(State1, Profile, DepsDir, AppInfo1, Locks, Level),
    AppInfo3 = rebar_app_info:dep_level(AppInfo2, Level),
    {NewDeps ++ Deps, [AppInfo3 | Apps], State2, NewSeen}.

-spec handle_dep(rebar_state:t(), atom(), file:filename_all(), rebar_app_info:t(), list(), integer()) -> {rebar_app_info:t(), [rebar_app_info:t()], rebar_state:t()}.
handle_dep(State, Profile, DepsDir, AppInfo, Locks, Level) ->
    Name = rebar_app_info:name(AppInfo),

    AppInfo1 = rebar_app_info:apply_overrides(rebar_app_info:get(AppInfo, overrides, []), AppInfo),
    AppInfo2 = rebar_app_info:apply_profiles(AppInfo1, [default, prod]),

    Plugins = rebar_app_info:get(AppInfo2, plugins, []),
    AppInfo3 = rebar_app_info:set(AppInfo2, {plugins, Profile}, Plugins),

    %% Will throw an exception if checks fail
    rebar_app_info:verify_otp_vsn(AppInfo3),

    %% 下载依赖的插件
    State1 = install(State, AppInfo3),

    %% Upgrade lock level to be the level the dep will have in this dep tree
    Deps = rebar_app_info:get(AppInfo3, {deps, default}, []) ++ rebar_app_info:get(AppInfo3, {deps, prod}, []),
    AppInfo4 = rebar_app_info:deps(AppInfo3, rebar_state:deps_names(Deps)),

    %% Keep all overrides from the global config and this dep when parsing its deps
    Overrides = rebar_app_info:get(AppInfo, overrides, []),
    Deps1 = rebar_app_utils:parse_deps(Name, DepsDir, Deps, rebar_state:set(State, overrides, Overrides)
        , Locks, Level + 1),
    {AppInfo4, Deps1, State1}.

-spec maybe_fetch(rebar_app_info:t(), atom(), boolean(),
    sets:set(binary()), rebar_state:t()) -> {ok, rebar_app_info:t()}.
maybe_fetch(AppInfo, _Profile, Upgrade, Seen, State) ->
    AppDir = rebar_utils:to_list(rebar_app_info:dir(AppInfo)),
    %% Don't fetch dep if it exists in the _checkouts dir
    case rebar_app_info:is_checkout(AppInfo) of
        true ->
            {ok, AppInfo};
        false ->
            case rebar_app_info:is_available(AppInfo) of
                false ->
                    AppInfo1 = fetch_app(AppInfo, State),
%%                    maybe_symlink_default(State, Profile, AppDir, AppInfo1),
                    {ok, rebar_app_info:is_available(rebar_app_info:valid(AppInfo1, false), true)};
                true ->
                    case sets:is_element(rebar_app_info:name(AppInfo), Seen) of
                        true ->
                            {ok, AppInfo};
                        false ->
%%                            maybe_symlink_default(State, Profile, AppDir, AppInfo),
                            AppInfo1 = maybe_upgrade(AppInfo, AppDir, Upgrade, State),
                            {ok, AppInfo1}
                    end
            end
    end.



fetch_app(AppInfo, State) ->
    rebar_api:info("Fetching ~ts", [rebar_resource_v2:format_source(AppInfo)]),
    case rebar_fetch:download_source(AppInfo, State) of
        {error, Reason} ->
            rebar_api:error("Download false:~p", [Reason]),
            rebar_api:abort();
        AppInfo1 ->
            To = rebar_app_info:fetch_dir(AppInfo1),
            rebar_api:info("Save to ~ts", [To]),
            AppInfo1
    end.

maybe_upgrade(AppInfo, _AppDir, Upgrade, State) ->
    case Upgrade orelse rebar_app_info:is_lock(AppInfo) of
        true ->
            case rebar_fetch:needs_update(AppInfo, State) of
                true ->
                    rebar_api:info("Upgrading ~ts", [rebar_resource_v2:format_source(AppInfo)]),
                    rebar_fetch:download_source(AppInfo, State);
                false ->
                    case Upgrade of
                        true ->
                            rebar_api:info("No upgrade needed for ~ts", [rebar_app_info:name(AppInfo)]),
                            AppInfo;
                        false ->
                            AppInfo
                    end
            end;
        false ->
            AppInfo
    end.

warn_skip_deps(AppInfo, State) ->
    Msg = "Skipping ~ts as an app of the same name "
    "has already been fetched",
    Args = [rebar_resource_v2:format_source(AppInfo)],
    case rebar_state:get(State, deps_error_on_conflict, false) of
        false ->
            case rebar_state:get(State, deps_warning_on_conflict, true) of
                true -> rebar_api:warn(Msg, Args);
                false -> ok
            end;
        true ->
            rebar_api:error(Msg, Args),
            rebar_api:abort()
    end.


find_app_and_level_by_name([], _) ->
    false;
find_app_and_level_by_name([App | Apps], Name) ->
    case rebar_app_info:name(App) of
        Name -> {ok, App, rebar_app_info:dep_level(App)};
        _ -> find_app_and_level_by_name(Apps, Name)
    end.

%% ========== 以下这些来自于 rebar_plugins.erl ==========

-spec project_plugins_install(rebar_state:t()) -> rebar_state:t().
project_plugins_install(State) ->
    Profiles = rebar_state:current_profiles(State),
    State1 = rebar_state:allow_provider_overrides(State, true),
    State3 = lists:foldl(
        fun(Profile, StateAcc) ->
            Plugins = rebar_state:get(State1, {project_plugins, Profile}, []),
            rebar_api:debug("project_plugins ~p", [Plugins]),
            {_Apps, State2} = handle_deps_as_profile(Profile, StateAcc, Plugins, false),
            State2
        end, State1, Profiles),
    rebar_state:allow_provider_overrides(State3, false).

-spec top_level_install(rebar_state:t()) -> rebar_state:t().
top_level_install(State) ->
    Profiles = rebar_state:current_profiles(State),
    lists:foldl(
        fun(Profile, StateAcc) ->
            Plugins = rebar_state:get(State, {plugins, Profile}, []),
            rebar_api:debug("top_level_install ~p", [Plugins]),
            {_Apps, State1} = handle_deps_as_profile(Profile, StateAcc, Plugins, false),
            State1
        end, State, Profiles).

%%-spec project_apps_install(rebar_state:t()) -> rebar_state:t().
%%project_apps_install(State) ->
%%    Profiles = rebar_state:current_profiles(State),
%%    ProjectApps = rebar_state:project_apps(State),
%%    lists:foldl(
%%        fun(Profile, StateAcc) ->
%%            StateAcc1 = case Profile of
%%                            default ->
%%                                %% default profile top level plugins
%%                                %% are installed in run_aux
%%                                StateAcc;
%%                            _ ->
%%                                Plugins = rebar_state:get(State, {plugins, Profile}, []),
%%                                handle_plugins(Profile, Plugins, StateAcc)
%%                        end,
%%            lists:foldl(
%%                fun(AppInfo, StateAcc2) ->
%%                    Plugins2 = rebar_app_info:get(AppInfo, {plugins, Profile}, []),
%%                    handle_plugins(Profile, Plugins2, StateAcc2)
%%                end, StateAcc1, ProjectApps)
%%        end, State, Profiles).

-spec install(rebar_state:t(), rebar_app_info:t()) -> rebar_state:t().
install(State, AppInfo) ->
    Profiles = rebar_state:current_profiles(State),

    %% don't lose the overrides of the dep we are processing plugins for
    Overrides = rebar_app_info:get(AppInfo, overrides, []),
    StateOverrides = rebar_state:get(State, overrides, []),
    AllOverrides = Overrides ++ StateOverrides,
    State1 = rebar_state:set(State, overrides, AllOverrides),

    State3 = lists:foldl(
        fun(Profile, StateAcc) ->
            Plugins = rebar_app_info:get(AppInfo, {plugins, Profile}, []),
            Plugins1 = filter_existing_plugins(Plugins, StateAcc),
            {_Apps, State2} = handle_deps_as_profile(Profile, StateAcc, Plugins1, false),
            State2
        end, State1, Profiles),

    %% Reset the overrides after processing the dep
    rebar_state:set(State3, overrides, StateOverrides).

filter_existing_plugins(Plugins, State) ->
    PluginNames = lists:zip(Plugins, rebar_state:deps_names(Plugins)),
    AllPlugins = rebar_state:all_plugin_deps(State),
    lists:filtermap(
        fun({Plugin, PluginName}) ->
            case rebar_app_utils:find(PluginName, AllPlugins) of
                {ok, _} ->
                    false;
                _ ->
                    {true, Plugin}
            end
        end, PluginNames).


%%build_plugins(MustBuildApps, AllApps, State) ->
%%    State1 = rebar_state:deps_to_build(State, MustBuildApps),
%%    State2 = rebar_state:all_deps(State1, AllApps),
%%    State3 = rebar_state:set(State2, deps_dir, ?DEFAULT_PLUGINS_DIR),
%%    {Args, Extra} = rebar_state:command_parsed_args(State),
%%    State4 = rebar_state:command_parsed_args(State3, {[{deps_only, true} | Args], Extra}),
%%    rebar_prv_compile:do(State4),
%%    ok.
%%
%%plugin_providers({Plugin, _, _, _}) when is_atom(Plugin) ->
%%    validate_plugin(Plugin);
%%plugin_providers({Plugin, _, _}) when is_atom(Plugin) ->
%%    validate_plugin(Plugin);
%%plugin_providers({Plugin, _}) when is_atom(Plugin) ->
%%    validate_plugin(Plugin);
%%plugin_providers(Plugin) when is_atom(Plugin) ->
%%    validate_plugin(Plugin).
%%
%%validate_plugin(Plugin) ->
%%    _ = application:load(Plugin),
%%    case application:get_env(Plugin, providers) of
%%        {ok, Providers} ->
%%            Providers;
%%        undefined ->
%%            Exports = Plugin:module_info(exports),
%%            case lists:member({init, 1}, Exports) of
%%                false ->
%%                    ?WARN("Plugin ~p does not export init/1. It will not be used.", [Plugin]),
%%                    [];
%%                true ->
%%                    [Plugin]
%%            end
%%    end.
